const CryptoJS = require('crypto-js');

function generateIV() {
  return CryptoJS.lib.WordArray.random(8);
}

const encryptAES = (data, key) => {
  iv = CryptoJS.enc.Utf8.parse(generateIV());
  console.log('IV: ', iv);
  const ciphertext = CryptoJS.AES.encrypt(
    JSON.stringify(data), 
    key,
    {   
        iv: iv, 
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
    }
  );
  return {
    iv: iv,
    ciphertext: ciphertext.toString()
  };
};

const decryptAES = (ciphertext, key, iv) => {
    const data = CryptoJS.AES.decrypt(
        ciphertext,
        key,
        {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }
    );
    return JSON.parse(data.toString(CryptoJS.enc.Utf8));
}

module.exports={
  encryptAES,
  decryptAES,
};